Razorpay Payment Gateway Integration in PHP

Razorpay Payment Gateway Integration in PHP

Creating a user add profile page with a payment requirement using Razorpay involves several steps. Here’s a guide to help you implement this functionality using HTML, JavaScript, and a backend (such as PHP) for handling the server-side logic.

1. Download Razorpay PHP SDK

  1. Go to the Razorpay PHP SDK GitHub repository. OR Razorpay-php/releases/
  2. Download the repository as a ZIP file and extract it into your project directory.

2. Frontend: HTML Form

Create an HTML form for user input as before.

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>User Profile</title>
</head>
<body>
    <h2>Create User Profile</h2>
    <form id="userForm">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name" required><br><br>
        
        <label for="dob">Date of Birth:</label>
        <input type="date" id="dob" name="dob" required><br><br>
        
        <label for="gender">Gender:</label>
        <select id="gender" name="gender" required>
            <option value="male">Male</option>
            <option value="female">Female</option>
            <option value="other">Other</option>
        </select><br><br>
        
        <button type="button" onclick="startPayment()">Submit</button>
    </form>

    <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
    <script>
        function startPayment() {
            var name = document.getElementById('name').value;
            var dob = document.getElementById('dob').value;
            var gender = document.getElementById('gender').value;
            
            // Validate form data
            if (name && dob && gender) {
                // Request for Razorpay order ID from backend
                fetch('/createOrder', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ amount: 500 }) // Example amount in paise
                })
                .then(response => response.json())
                .then(data => {
                    var options = {
                        "key": "YOUR_RAZORPAY_KEY", // Enter your Razorpay key here
                        "amount": data.amount, // Amount in paise
                        "currency": "INR",
                        "name": "Your Company Name",
                        "description": "Payment for User Profile",
                        "order_id": data.order_id, // Razorpay order ID
                        "handler": function (response){
                            // Handle successful payment
                            fetch('/verifyPayment', {
                                method: 'POST',
                                headers: {
                                    'Content-Type': 'application/json'
                                },
                                body: JSON.stringify({
                                    razorpay_payment_id: response.razorpay_payment_id,
                                    razorpay_order_id: response.razorpay_order_id,
                                    razorpay_signature: response.razorpay_signature,
                                    user: { name, dob, gender }
                                })
                            })
                            .then(response => response.json())
                            .then(data => {
                                if (data.success) {
                                    alert("Payment Successful. User Profile Created.");
                                } else {
                                    alert("Payment Failed. Please try again.");
                                }
                            });
                        },
                        "prefill": {
                            "name": name,
                            "email": "user@example.com", // Add user email if available
                        },
                        "theme": {
                            "color": "#3399cc"
                        }
                    };
                    var rzp1 = new Razorpay(options);
                    rzp1.open();
                });
            } else {
                alert('Please fill all the fields');
            }
        }
    </script>
</body>
</html>

 

3. Backend: PHP

createOrder.php:

<?php
require('razorpay-php/Razorpay.php');

use Razorpay\Api\Api;

$api = new Api('YOUR_RAZORPAY_KEY_ID', 'YOUR_RAZORPAY_KEY_SECRET');

$amount = 500; // Amount in paise

$order = $api->order->create(array(
    'receipt' => 'order_rcptid_11',
    'amount' => $amount,
    'currency' => 'INR'
));

echo json_encode($order);
?>

verifyPayment.php:

<?php
require('razorpay-php/Razorpay.php');

use Razorpay\Api\Api;
use Razorpay\Api\Errors\SignatureVerificationError;

$api = new Api('YOUR_RAZORPAY_KEY_ID', 'YOUR_RAZORPAY_KEY_SECRET');

$input = file_get_contents('php://input');
$data = json_decode($input, true);

$razorpay_order_id = $data['razorpay_order_id'];
$razorpay_payment_id = $data['razorpay_payment_id'];
$razorpay_signature = $data['razorpay_signature'];
$user = $data['user'];

$success = false;
$error = '';

try {
    $attributes = array(
        'razorpay_order_id' => $razorpay_order_id,
        'razorpay_payment_id' => $razorpay_payment_id,
        'razorpay_signature' => $razorpay_signature
    );

    $api->utility->verifyPaymentSignature($attributes);
    $success = true;
} catch (SignatureVerificationError $e) {
    $error = 'Razorpay Error : ' . $e->getMessage();
}

if ($success) {
    // Save user details to the database (pseudo code)
    // $db->saveUser($user);
    echo json_encode(['success' => true, 'message' => 'Payment verified successfully']);
} else {
    echo json_encode(['success' => false, 'message' => $error]);
}
?>

4. Integration and Testing

  • Ensure you replace YOUR_RAZORPAY_KEY and YOUR_RAZORPAY_KEY_SECRET with your actual Razorpay credentials.
  • Test the entire flow: form submission, Razorpay payment, and verification.
  • Save user data upon successful payment.

This setup allows you to create a user profile page with Razorpay payment integration in PHP without using Composer. Adjust the code as necessary to fit your specific requirements and environment.

We care about your data and would love to use cookies to improve your experience.